package com.skhu.as.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.skhu.as.domain.Worker;
import com.skhu.as.service.WorkerS;

public class WorkerC extends SimpleFormController {

	private WorkerS workerS;

	public void setWorkerS(WorkerS workerS) {
		this.workerS = workerS;
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		
		if(!isFormSubmission(request)){
			String method = ServletRequestUtils.getStringParameter(request, "method", "");			
			if(!method.equals("")){
				int workerNo = ServletRequestUtils.getIntParameter(request, "workerNo");
				workerS.deleteWorker(workerNo);
			}
		}
		
		return super.formBackingObject(request);
	}
	
	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
		
		List<Worker> workerList = workerS.getWorkerList();
		
		Map ref = new HashMap();
		ref.put("workerList", workerList);
		
		return ref;
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		int workerMaxNo = workerS.getWorkerMaxNo();
		
		Worker worker = (Worker)command;
		worker.setWorkerNo(workerMaxNo + 1);

		workerS.insertWorker(worker);
		
		return super.onSubmit(request, response, command, errors);
	}
	
}
